
import  Storage  from '../store';
export const headers = {
    "Content-Type": "application/json",
    'Access-Control-Allow-Origin': '*',
    'auth-token': $.cookie('auth-token'),
    // 'roles': JSON.stringify(getCurrentLoginUser),
    "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
}

export const FetchAPI = (url, method, data) => {
    Storage.dispatch({type:"REQUEST",data:true});
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: method,
            // headers:{...headers,'auth-token': $.cookie('auth-token')},
            headers:{...headers},
            body: data?JSON.stringify(data):null,
        }).then(checkStatus).then(parseJSON).then(filterResponse).then((data) => {
            resolve(data);

        }).catch((err) => {
            reject({err});
        }).finally(()=>{
            Storage.dispatch({type:"FINISH",data:false});
        });
    })
}

export function checkStatus(response) {
    if ((response.status >= 200 && response.status < 300) || response.status == 400) {
        return response
    } else {
        var err = new Error("网络异常")
        err.response = response
        err.message = response.statusText
        throw err
    }
}

export function parseJSON(response) {
    if (response.ok || response.status == '400') {
        return response.json();
    } else {
        return {err: {msg: '请求异常', code: '6666'}}
    }
}

//后端交互限制
export function filterResponse(data) {
    var patten = /^ACM\d{4}$/;
    if (patten.test(data.code)) {
        return data
    } else {
        var error = new Error(data.message)
        throw error
    }

}